package com.lp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lp
 * 2017/11/7 17:18
 */
@Aspect
@Component
public class HttpAspect {
//  方式一
//    //@Before("execution(public * com.lp.controller.GirlController.girlList(..))")
//    @Before("execution(public * com.lp.controller.GirlController.*(..))")
//    private void log(){
//        System.out.println("Before ......");
//    }
//
//    @After("execution(public * com.lp.controller.GirlController.*(..))")
//    private void doAfter(){
//        System.out.println("After ......");
//    }

////  方式二
//    @Pointcut("execution(public * com.lp.controller.GirlController.*(..))")
//    private void log(){
//    }
//
//    @Before("log()")
//    private void doBefore(){
//        System.out.println("Before ......");
//    }
//
//    @After("log()")
//    private void doAfter(){
//        System.out.println("After ......");
//    }

    //  方式三:改造log记录方式,并记录具体内容

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.lp.controller.GirlController.*(..))")
    private void log(){
    }

    @Before("log()")
    private void doBefore(JoinPoint joinPoint){
        logger.info("Before ......");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURL());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //类方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        //参数
        logger.info("args={}",joinPoint.getArgs());
    }

    @After("log()")
    private void doAfter(){
        logger.info("After ......");
    }

    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        logger.info("response={}",object);
    }
}
